package com.yonyou.cyxdms.basedata.service.service.model;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yonyou.cloud.http.plus.remote.IRemoteInvoke;
import com.yonyou.cyx.framework.compent.redis.RedisClient;
import com.yonyou.cyx.framework.service.excel.*;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.bean.dto.ImportResultDto;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.bean.BeanMapperUtil;
import com.yonyou.cyx.function.utils.common.CommonUtils;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyx.function.utils.jsonserializer.JSONUtil;
import com.yonyou.cyxdms.basedata.client.constants.BaseDataCommonConstants;
import com.yonyou.cyxdms.basedata.client.constants.BaseDataDictConstants;
import com.yonyou.cyxdms.basedata.client.domains.vo.MQBaseVO;
import com.yonyou.cyxdms.basedata.client.domains.vo.ModelCacheVO;
import com.yonyou.cyxdms.basedata.client.domains.vo.SeriesCacheVO;
import com.yonyou.cyxdms.basedata.service.constant.BasedataCommonConstants;
import com.yonyou.cyxdms.basedata.service.constant.BasedataDictConstants;
import com.yonyou.cyxdms.basedata.service.constant.CommonConstant;
import com.yonyou.cyxdms.basedata.service.dto.vehiclemodel.*;
import com.yonyou.cyxdms.basedata.service.entity.brand.BrandPO;
import com.yonyou.cyxdms.basedata.service.entity.model.ModelPO;
import com.yonyou.cyxdms.basedata.service.entity.series.SeriesPO;
import com.yonyou.cyxdms.basedata.service.repository.basedata.SystemParamMapper;
import com.yonyou.cyxdms.basedata.service.repository.brand.BrandMapper;
import com.yonyou.cyxdms.basedata.service.repository.model.ModelMapper;
import com.yonyou.cyxdms.basedata.service.repository.series.SeriesMapper;
import com.yonyou.cyxdms.basedata.service.service.brand.BrandService;
import com.yonyou.cyxdms.basedata.service.service.product.VsProductService;
import com.yonyou.cyxdms.basedata.service.service.series.SeriesService;
import com.yonyou.cyxdms.basedata.service.util.MQUtils;
import com.yonyou.cyxdms.basedata.service.util.MapUtils;
import com.yonyou.cyxdms.basedata.service.vo.CarparamInVO;
import com.yonyou.cyxdms.basedata.service.vo.CarparamInfoVO;
import com.yonyou.cyxdms.basedata.service.vo.GroupCarparamInVO;
import com.yonyou.cyxdms.basedata.service.vo.VsProductDlrVO;
import com.yonyou.cyxdms.basedata.service.vo.model.GmsModelVO;
import com.yonyou.cyxdms.basedata.service.vo.model.ModelDictVO;
import com.yonyou.cyxdms.basedata.service.vo.model.VehicleProductModelVO;
import com.yonyou.cyxdms.basedata.service.vo.packages.PackageDictVO;
import com.yonyou.cyxdms.basedata.service.vo.series.VehicleProductSeriesVO;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysmanage.client.service.login.DealerBrandService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.MessageFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 车型
 *
 * @author renwd
 * @since 2018/12/11
 */

@Service
@Transactional(rollbackFor = Exception.class)
public class ModelServiceImpl implements ModelService {

    public static final Logger logger = LoggerFactory.getLogger(ModelServiceImpl.class);

    @Autowired
    private BrandService brandService;

    @Autowired
    private SeriesService seriesService;

    @Autowired
    private ModelMapper modelMapper;

    @Autowired
    private SeriesMapper seriesMapper;

    @Autowired
    private ExcelGenerator excelService;

    @Autowired
    private ExcelRead<ModelImportDTO> excelModelService;

    @Autowired
    DealerBrandService dealerBrandService;

    @Autowired
    VsProductService vsProductService;

    @Autowired
    SystemParamMapper systemParamMapper;

    @Autowired
    IRemoteInvoke iRemoteInvoke;

    @Autowired
    private RedisClient redisClient;
    @Autowired
    BrandMapper brandMapper;

    /**
     * 按条件查询车型信息
     *
     * @param queryParam
     * @return java.util.List<com.yonyou.cyxdms.basedata.client.domains.DTO.basedata.ModelCacheVO>
     * @author renwd
     * @since 2018/12/11
     */
    @Override
    @Transactional(readOnly = true)
    public List<ModelCacheVO> queryModelByCondition(Map<String, Object> queryParam) {
        //获取所有品牌
        List<BrandPO> brandPos = brandMapper.selectList(new LambdaQueryWrapper<BrandPO>().eq(BrandPO::getAppId, CommonConstant.APP_ID_RL));
        List<Long> brandIdList = brandPos.stream().map(t -> t.getBrandId()).collect(Collectors.toList());

        queryParam.put(BasedataCommonConstants.DEALER_BRNAND_LIST, brandIdList);
        return modelMapper.queryModelByCondition(queryParam);
    }

    /**
     * 根据车系id查询车型信息
     *
     * @param seriesId
     * @return java.util.List<com.yonyou.cyxdms.basedata.client.domains.DTO.basedata.ModelCacheVO>
     * @author guorp
     * @since 2018/12/13
     */
    @Override
    public List<ModelCacheVO> getModelBySeriesId(Long seriesId) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return modelMapper.getModelBySeriesId(seriesId, loginInfo.getAppId(), loginInfo.getGroupCode());
    }

    @Override
    public List<ModelCacheVO> allModel() {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        String dealerCode = loginInfo.getOwnerCode();
        return modelMapper.allModel(dealerCode, loginInfo.getAppId());
    }

    @Override
    public IPage<CarparamInfoVO> queryCarparamInfo(Long brandId, Long carserialId, Long pageNum, Long pageSize) {
        Page<CarparamInfoVO> page = new Page<>(pageNum, pageSize);
        List<CarparamInfoVO> carparamInfoVo = null;
        page.setRecords(carparamInfoVo);
        return page;
    }

    /**
     * 根据车系ID列表查询车型信息
     *
     * @author dengqiang
     * @since 2019/1/7
     */
    @Override
    public List<GroupCarparamInVO> queryCarparamInfo(Long carserialId) {
        List<CarparamInVO> carParamInVo = null;
        return vsProductService.getCarparamInfo(carParamInVo);
    }

    /**
     * 查询车型信息（pc）
     *
     * @param page
     * @param modelQueryDTO
     * @author Tansj
     * @since 2019/11/15
     */
    @Override
    public IPage<VehicleProductModelVO> queryVehicleProductModel(Page page, ModelQueryDTO modelQueryDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map<String, Object> queryParam = modelQueryDTO.toMaps();
        queryParam = brandService.setLoginInfoParam(queryParam, loginInfoDto);
        logger.info("查询车型IPage的queryParam:------------------{}", queryParam);
        /**
         * 车型数据放置redis
         */
        String appId = loginInfoDto.getAppId();
        String  messageFormat = MessageFormat.format(BasedataCommonConstants.MODEL_CACHE_PRODUCT_MODELID, appId);
        Object modelData = redisClient.get(messageFormat);
        if (null == modelData) {
            LambdaQueryWrapper<ModelPO> modelParam = new QueryWrapper<ModelPO>().lambda();
            modelParam.eq(ModelPO::getAppId, appId).orderByAsc(ModelPO::getModelCode,ModelPO::getIsDeleted);
            List<ModelPO> modelList = modelMapper.selectList(modelParam);
            List<ModelCacheVO> modelVOList = BeanMapperUtil.copyList(modelList, ModelCacheVO.class);
            redisClient.set(messageFormat, JSONUtil.objectToJson(modelVOList), BaseDataCommonConstants.EXPIRE_TIME_ONE_DAY);
        }
        page.setRecords(modelMapper.queryVehicleProductModel(page, queryParam));
        return page;
    }

    /**
     * dcs查询车型信息
     *
     * @param page
     * @param queryParam
     * @return com.baomidou.mybatisplus.core.metadata.IPage<com.yonyou.cyxdms.basedata.service.vo.model.VehicleProductModelVO>
     * @author renwd
     * @since 2019/7/18
     */
    @Override
    public IPage<GmsModelVO> queryVehicleProductDcsModel(Page page, Map<String, Object> queryParam) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        MapUtils.addParameter(queryParam, loginInfo.getOwnerCode(), loginInfo.getAppId(), loginInfo.getGroupCode());
        queryParam.put(BasedataCommonConstants.ORG_TYPE, loginInfo.getOrgType());
        queryParam.put(BasedataCommonConstants.DATA_SOURCES, BasedataDictConstants.DATA_SOURCES_BY_SUPER);
        page.setRecords(modelMapper.queryVehicleProductDcsModel(page, queryParam));
        return page;
    }

    /**
     * 新增车型
     *
     * @param modelDTO
     * @return java.lang.Integer
     * @author Tansj
     * @since 2019/11/15
     */
    @Override
    public Integer addModel(ModelModifyDTO modelDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        QueryWrapper<ModelPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(ModelPO::getAppId, loginInfoDto.getAppId())
                .in(ModelPO::getOwnerCode, loginInfoDto.getOwnerCode())
                .and(obj ->
                        obj.eq(ModelPO::getModelCode, modelDTO.getModelCode())
                                .or()
                                .eq(ModelPO::getModelName, modelDTO.getModelName()));
        // 判断同一家店面中是否存在相同的车型代码或名称
        List<ModelPO> modelPo = modelMapper.selectList(queryWrapper);
        if (!CommonUtils.isNullOrEmpty(modelPo)) {
            throw new ServiceBizException(BasedataCommonConstants.MODEL_NOT_REPEAT);
        }
        ModelPO modelPos = BeanMapperUtil.copyProperties(modelDTO, ModelPO.class);
        int insertSize = modelMapper.insert(modelPos);
        // 车型数据发送到MQ
        sendModel(modelPos, BasedataCommonConstants.BIZ_MODEL_INSERT);
        // 删除redis缓存
        String messageFormat = MessageFormat.format(BaseDataCommonConstants.MODEL_CACHE_MODEL_ALL, loginInfoDto.getAppId(), loginInfoDto.getOwnerCode());
        redisClient.del(messageFormat);

        return insertSize;
    }

    /**
     * dcs新增车型
     *
     * @param modelDTO
     * @return java.lang.Integer
     * @author Tansj
     * @since 2019/11/15
     */
    @Override
    public Integer addDcsModel(ModelModifyDTO modelDTO) {
        String appId = BasedataCommonConstants.APP_ID_RL;
        String groupCode = "-1";
        QueryWrapper<ModelPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(ModelPO::getAppId, appId)
                .and(obj ->
                        obj.eq(ModelPO::getModelCode, modelDTO.getModelCode()));
        // 判断同一家店面中是否存在相同的车型代码或名称
        List<ModelPO> modelPos = modelMapper.selectList(queryWrapper);
        if (!CommonUtils.isNullOrEmpty(modelPos)) {
            return 0;
        }
        ModelPO modelPo = BeanMapperUtil.copyProperties(modelDTO, ModelPO.class);
        modelPo.setDataSources(BasedataDictConstants.DATA_SOURCES_BY_SUPER);
        modelPo.setAppId(BasedataCommonConstants.APP_ID_RL);
        modelPo.setCompanyCode("-1");
        modelPo.setOwnerCode("-1");
        modelPo.setOwnerParCode("-1");
        modelPo.setIsIssue(BasedataDictConstants.IS_NO_SEND);
        int insertSize = modelMapper.insert(modelPo);
        // 删除redis缓存
        String messageFormat = MessageFormat.format(BaseDataCommonConstants.MODEL_CACHE_MODEL_ALL, appId, groupCode);
        redisClient.del(messageFormat);
        String productFormat = MessageFormat.format(BaseDataCommonConstants.PRODUCT_CACHE_DATA, appId, BasedataCommonConstants.PRODUCT_REDIS_TYPE, BasedataCommonConstants.PRODUCT_REDIS_LEVEL);
        redisClient.del(productFormat);
        return insertSize;
    }

    /**
     * 车型数据发送到MQ
     *
     * @param modelPo
     * @author ysj
     * @date 2019/10/23
     */
    public void sendModel(ModelPO modelPo, String bizId) {
        List<ModelPO> modelList = new ArrayList<>();
        modelList.add(modelPo);
        MQBaseVO<List<ModelPO>> modelMq = new MQBaseVO<>(modelList, modelPo.getAppId(), modelPo.getOwnerCode());
        MQUtils.sendMsg(modelMq.toMap(), bizId, systemParamMapper, iRemoteInvoke);
    }

    /**
     * 修改车型
     *
     * @param id
     * @param modelDto
     * @return Integer
     * @author Tansj
     * @since 2019/11/15
     */
    @Override
    public Integer modifyModel(Long id, ModelModifyDTO modelDto) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        ModelPO modelPo = modelMapper.selectById(id);
        if (modelPo != null) {
            QueryWrapper<ModelPO> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(ModelPO::getAppId, loginInfoDto.getAppId())
                    .in(ModelPO::getOwnerCode, loginInfoDto.getOwnerCode())
                    .notIn(ModelPO::getModelId, id)
                    .and(obj ->
                            obj.eq(ModelPO::getModelCode, modelDto.getModelCode())
                                    .or()
                                    .eq(ModelPO::getModelName, modelDto.getModelName()));
            // 判断同一家店面是否存在相同的车型代码或名称
            List<ModelPO> modelPos = modelMapper.selectList(queryWrapper);
            if (!CommonUtils.isNullOrEmpty(modelPos)) {
                throw new ServiceBizException(BasedataCommonConstants.MODEL_NOT_REPEAT);
            }
            modelPo.setBrandId(modelDto.getBrandId());
            modelPo.setSeriesId(modelDto.getSeriesId());
            modelPo.setModelCode(modelDto.getModelCode());
            modelPo.setModelName(modelDto.getModelName());
            modelPo.setDataSources(modelDto.getDataSources());
            modelPo.setIsValid(modelDto.getIsValid());
            modelPo.setRecordVersion(modelDto.getRecordVersion());
            modelPo.setStartDate(modelDto.getStartDate());
            modelPo.setCommonPlatformFlag(modelDto.getCommonPlatformFlag());
            modelPo.setUpdatedAt(LocalDateTime.now());
            int updateSize = modelMapper.updateById(modelPo);
            // 删除redis缓存
            String messageFormat = MessageFormat.format(BaseDataCommonConstants.MODEL_CACHE_MODEL_ALL, loginInfoDto.getAppId(), loginInfoDto.getOwnerCode());
            redisClient.del(messageFormat);
            if (updateSize != 0) {
                // 车型数据发送到MQ
                sendModel(modelPo, BasedataCommonConstants.BIZ_MODEL_UPDATE);
                return updateSize;
            } else {
                throw new ServiceBizException(BasedataCommonConstants.UPDATE_FAILED);
            }
        } else {
            throw new ServiceBizException("后台不存在该车型！");
        }
    }

    /**
     * dcs修改车型
     *
     * @param id
     * @param modelDto
     * @return Integer
     * @author Tansj
     * @since 2019/11/15
     */
    @Override
    public Integer modifyDcsModel(Long id, ModelModifyDTO modelDto) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        ModelPO modelPo = modelMapper.selectById(id);
        if (modelPo != null) {
            QueryWrapper<ModelPO> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(ModelPO::getAppId, loginInfoDto.getAppId())
                    .in(ModelPO::getOwnerCode, loginInfoDto.getGroupCode(), "-1")
                    .notIn(ModelPO::getModelId, id)
                    .and(obj ->
                            obj.eq(ModelPO::getModelCode, modelDto.getModelCode())
                                    .or()
                                    .eq(ModelPO::getModelName, modelDto.getModelName()));
            // 判断同一家店面是否存在相同的车型代码或名称
            List<ModelPO> modelPos = modelMapper.selectList(queryWrapper);
            if (!CommonUtils.isNullOrEmpty(modelPos)) {
                throw new ServiceBizException(BasedataCommonConstants.MODEL_NOT_REPEAT);
            }
            modelPo.setBrandId(modelDto.getBrandId());
            modelPo.setSeriesId(modelDto.getSeriesId());
            modelPo.setModelCode(modelDto.getModelCode());
            modelPo.setModelName(modelDto.getModelName());
            modelPo.setIsValid(modelDto.getIsValid());
            modelPo.setRecordVersion(modelDto.getRecordVersion());
            modelPo.setUpdatedAt(LocalDateTime.now());
            modelPo.setIsIssue(BasedataDictConstants.IS_NO_SEND);
            int updateSize = modelMapper.updateById(modelPo);
            // 删除redis缓存
            String messageFormat = MessageFormat.format(BaseDataCommonConstants.MODEL_CACHE_MODEL_ALL, loginInfoDto.getAppId(), loginInfoDto.getGroupCode());
            redisClient.del(messageFormat);
            String productFormat = MessageFormat.format(BaseDataCommonConstants.PRODUCT_CACHE_DATA, loginInfoDto.getAppId(), BasedataCommonConstants.PRODUCT_REDIS_TYPE, BasedataCommonConstants.PRODUCT_REDIS_LEVEL);
            redisClient.del(productFormat);
            if (updateSize != 0) {
                // 车型数据发送到MQ
                sendModel(modelPo, BasedataCommonConstants.BIZ_MODEL_UPDATE);
                return updateSize;
            } else {
                throw new ServiceBizException(BasedataCommonConstants.UPDATE_FAILED);
            }
        } else {
            throw new ServiceBizException("后台不存在该车型！");
        }
    }

    /**
     * 车型导出excel
     *
     * @param queryParam
     * @param request
     * @param response
     * @return void
     * @author renwd
     * @since 2019/7/15
     */
    @Override
    public void exportExcelForModel(Map<String, Object> queryParam, HttpServletRequest request, HttpServletResponse response) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        MapUtils.addParameter(queryParam, loginInfoDto.getOwnerCode(), loginInfoDto.getAppId(), loginInfoDto.getGroupCode());

        List<Long> brandIdList = dealerBrandService.queryBrandIdList();
        queryParam.put(BasedataCommonConstants.DEALER_BRNAND_LIST, brandIdList);
        List<Map> resultList = modelMapper.exportExcelForModel(queryParam);
        Map<String, List<Map>> excelData = new HashMap<>();
        excelData.put("车型信息", resultList);
        List<ExcelExportColumn> exportColumnList = new ArrayList<>();
        exportColumnList.add(new ExcelExportColumn("BRAND_NAME", "品牌名称"));
        exportColumnList.add(new ExcelExportColumn("SERIES_NAME", "车系名称"));
        exportColumnList.add(new ExcelExportColumn("MODEL_CODE", "车型代码"));
        exportColumnList.add(new ExcelExportColumn("MODEL_NAME", "车型名称"));
        exportColumnList.add(new ExcelExportColumn("IS_VALID", "是否有效", ExcelDataType.Dict));
        excelService.generateExcel(excelData, exportColumnList, "车型信息.xls", request, response);
    }

    /**
     * 车型下拉框
     *
     * @param queryParam
     * @return java.util.List<com.yonyou.cyxdms.basedata.service.vo.model.ModelDictVO>
     * @author renwd
     * @since 2019/7/16
     */
    @Override
    public List<ModelDictVO> queryModelDict(Map<String, Object> queryParam) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        MapUtils.addParameter(queryParam, loginInfo.getOwnerCode(), loginInfo.getAppId(), loginInfo.getGroupCode());
        queryParam.put(BasedataCommonConstants.ORG_TYPE, loginInfo.getOrgType());
        queryParam.put("isValid", BaseDataDictConstants.IS_VALID);
        return modelMapper.queryModelDict(queryParam);
    }

    /**
     * dms端 查询集团端
     *
     * @param queryParam
     * @return java.util.List<com.yonyou.cyxdms.basedata.service.vo.model.GmsModelVO>
     * @author renwd
     * @since 2019/7/18
     */
    @Override
    public List<GmsModelVO> queryGmsModel(Map<String, Object> queryParam) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        MapUtils.addParameter(queryParam, loginInfo.getOwnerCode(), loginInfo.getAppId(), loginInfo.getGroupCode());
        queryParam.put(BasedataCommonConstants.ORG_TYPE, loginInfo.getOrgType());
        queryParam.put("dataSources", BasedataDictConstants.DATA_SOURCES_BY_GROUP);
        return modelMapper.queryGmsModel(queryParam);
    }

    /**
     * 导入车型
     *
     * @param importFile
     * @return java.util.List<com.yonyou.cyxdms.basedata.service.dto.vehiclemodel.ModelImportDTO>
     * @author renwd
     * @since 2019/7/22
     */
    @Override
    public List<ModelImportDTO> importModel(MultipartFile importFile) {
        ImportResultDto<ModelImportDTO> importResult = null;
        try {
            importResult = excelModelService.analyzeExcelFirstSheet(importFile,
                    new AbstractExcelReadCallBack<>(ModelImportDTO.class, this::addModelImport));
            return importResult.getDataList();
        } catch (IOException e) {
            logger.error("import error:{}", e);
        }
        return Collections.emptyList();
    }

    /**
     * 车型是否存在
     *
     * @param modelName
     * @return com.yonyou.cyxdms.basedata.service.entity.model.ModelPO
     * @author renwd
     * @since 2019/7/22
     */
    @Override
    public ModelPO existsSeries(String modelName) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        QueryWrapper<ModelPO> modelPoQueryWrapper = new QueryWrapper<>();
        modelPoQueryWrapper.lambda().eq(ModelPO::getModelName, modelName)
                .eq(ModelPO::getAppId, loginInfoDto.getAppId())
                .in(ModelPO::getOwnerCode, loginInfoDto.getOwnerCode(), "-1");
        ModelPO modelPo = modelMapper.selectOne(modelPoQueryWrapper);
        if (StringUtils.isNullOrEmpty(modelPo)) {
            throw new ServiceBizException("车型名称不存在");
        }
        return modelPo;
    }

    /**
     * 导入车型
     *
     * @param rowDto
     * @return void
     * @author renwd
     * @since 2019/7/22
     */
    private void addModelImport(ModelImportDTO rowDto, boolean isValidateSucess) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        QueryWrapper<ModelPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ModelPO::getModelCode, rowDto.getModelCode())
                .eq(ModelPO::getAppId, loginInfoDto.getAppId())
                .in(ModelPO::getOwnerCode, loginInfoDto.getOwnerCode(), loginInfoDto.getGroupCode(), "-1");
        List<ModelPO> list = modelMapper.selectList(queryWrapper);
        if (!CommonUtils.isNullOrEmpty(list)) {
            throw new ServiceBizException(BasedataCommonConstants.MODEL_NOT_REPEAT);
        }

        brandService.existsBrand(rowDto.getBrandName());
        SeriesPO seriesPo = seriesService.existsSeries(rowDto.getSeriesName());

        ModelPO modelPo = new ModelPO();
        modelPo.setModelCode(rowDto.getModelCode());
        modelPo.setModelName(rowDto.getModelName());
        modelPo.setSeriesId(seriesPo.getSeriesId());

        String dataSources = rowDto.getDataSources();
        if (StringUtils.isNullOrEmpty(dataSources)) {
            modelPo.setDataSources(null);
        } else if ("店面".equals(dataSources)) {
            modelPo.setDataSources(10451001);
        } else if ("主机厂".equals(dataSources)) {
            modelPo.setDataSources(10451002);
        } else if ("集团".equals(dataSources)) {
            modelPo.setDataSources(10451003);
        } else {
            throw new ServiceBizException("数据来源不存在");
        }

        String isValid = rowDto.getIsValid();
        if (StringUtils.isNullOrEmpty(isValid)) {
            modelPo.setIsValid(null);
        } else if ("是".equals(isValid)) {
            modelPo.setIsValid(10041001);
        } else if ("否".equals(isValid)) {
            modelPo.setIsValid(10041002);
        } else {
            throw new ServiceBizException("是否有效类型不存在");
        }

        if (isValidateSucess) {
            modelMapper.insert(modelPo);
            //车型数据发送到MQ
            sendModel(modelPo, BasedataCommonConstants.BIZ_MODEL_INSERT);
        }
    }

    /**
     * @Description: 根据Code获取车型
     * @Param: [seriesId, appId, modelCode]
     * @Return: com.yonyou.cyxdms.basedata.service.vo.model.ModelDictVO
     * @Author: lijun
     * @Date: 16:05 2019/8/22
     **/
    @Override
    public ModelDictVO getByCode(String appId, Long seriesId, String modelCode) {
        return modelMapper.getByCode(appId, seriesId, modelCode);
    }

    /**
     * 通过appId与车型名称查询对应车型
     *
     * @param:
     * @return:
     * @auther: tanjie
     * @since: 2019/9/6
     */
    @Override
    public Long queryModelBynameAndAppid(String appId, String modelName) {
        List<ModelPO> modelPos = modelMapper.getModelByAppidAndName(appId, modelName);
        return !CommonUtils.isNullOrEmpty(modelPos) ? modelPos.get(0).getModelId() : null;
    }

    /**
     * code与id关系映射
     *
     * @param:
     * @return:
     * @auther: tanjie
     * @since: 2019/9/10
     */
    @Override
    public List<Map<String, Object>> queryModelMapping(String appId) {
        LambdaQueryWrapper<ModelPO> query = new QueryWrapper<ModelPO>().lambda();
        query.eq(ModelPO::getAppId, appId);
        List<ModelPO> modelPos = modelMapper.selectList(query);
        Collection<Map<String, Object>> maps = BeanMapperUtil.toMapList(modelPos);
        List<Map<String, Object>> result = new ArrayList<>();
        result.addAll(maps);
        return result;
    }


    /**
     * 获取所有车型接口
     * 未登陆接口
     *
     * @param:
     * @return:
     * @auther: tanjie
     * @since: 2019/10/8
     */
    @Override
    public Map<Object, Object> getAllByAppId(String appId, String requestId, Long recordTime) {

        if (null == appId || appId.trim() == "") {
            throw new ServiceBizException("未传入appId");
        }
        HashMap<Object, Object> resultMap = new HashMap<>();
        //是否需要根据时间戳进行查询
        LocalDateTime updateTime = null;
        if (null != recordTime) {
            Instant instant = Instant.ofEpochMilli(recordTime);
            updateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        }
        List<ModelPO> modelList = modelMapper.selectModelByUpdateTime(appId, updateTime);

        List<Map<String, Object>> result = new ArrayList<>();
        //联级查询车型,车系。品牌。
        for (ModelPO modelCache : modelList) {
            result.add(this.modelMapper.queryAllCode(modelCache.getModelId()));
        }
        resultMap.put("list", result);
        resultMap.put("requestid", requestId);
        //获取最新更新时间作为下次请求时间戳
        modelList.sort((o1, o2) -> (int) (o2.getUpdatedAt().toInstant(ZoneOffset.of("+8")).toEpochMilli() - o1.getUpdatedAt().toInstant(ZoneOffset.of("+8")).toEpochMilli()));
        resultMap.put("recordTime", CommonUtils.isNullOrEmpty(modelList) ? null :
                modelList.get(0).getUpdatedAt().toInstant(ZoneOffset.of("+8")).toEpochMilli());
        return resultMap;
    }


    /**
     * 通用——新增/更新车型
     *
     * @param generalModelDtos
     * @return java.lang.integer
     * @author chenzb
     * @since 2019/10/12
     */
    @Override
    public void addModelGeneral(List<GeneralModelDTO> generalModelDtos) {
        logger.debug("厂端同步至后台的车型数据:{}", generalModelDtos);
        if (CollectionUtils.isNotEmpty(generalModelDtos)) {
            // 数据不为空遍历存储
            for (GeneralModelDTO generalModelDTO : generalModelDtos) {
                QueryWrapper<ModelPO> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(ModelPO::getAppId, generalModelDTO.getAppId())
                        .eq(ModelPO::getSourceId, generalModelDTO.getSourceId());
                ModelPO oldModelPo = modelMapper.selectOne(queryWrapper);
                // 根据seriesCode获取车系信息-获取到该车系的id和品牌id
                QueryWrapper<SeriesPO> seriesPoWrapper = new QueryWrapper<>();
                seriesPoWrapper.lambda().eq(SeriesPO::getAppId, generalModelDTO.getAppId())
                        .eq(SeriesPO::getSeriesCode, generalModelDTO.getSeriesCode());
                SeriesPO seriesDictVO = seriesMapper.selectOne(seriesPoWrapper);
                String ownerCode = StringUtils.isBlank(generalModelDTO.getOwnerCode()) ? "-1" : generalModelDTO.getOwnerCode();
                // ownerCode设值-1 标记车厂下发
                if (oldModelPo == null) {
                    // 新增品牌
                    ModelPO modelPo = BeanMapperUtil.copyProperties(generalModelDTO, ModelPO.class);
                    modelPo.setOwnerCode(ownerCode);
                    modelPo.setCompanyCode(ownerCode);
                    modelPo.setOwnerParCode(ownerCode);
                    modelPo.setSourceChangedAt(LocalDateTime.now());
                    modelPo.setCreatedAt(LocalDateTime.now());
                    logger.debug("开始新增插入车型数据:{}", modelPo);
                    modelPo.setIsValid(10041001);
                    modelPo.setBrandId(Long.parseLong(seriesDictVO.getBrandId().toString()));
                    modelPo.setSeriesId(Long.parseLong(seriesDictVO.getSeriesId().toString()));
                    modelMapper.insert(modelPo);
                } else {
                    // 更新品牌
                    ModelPO modelPo = BeanMapperUtil.copyProperties(generalModelDTO, ModelPO.class);
                    modelPo.setOwnerCode(ownerCode);
                    modelPo.setCompanyCode(ownerCode);
                    modelPo.setOwnerParCode(ownerCode);
                    modelPo.setModelId(oldModelPo.getModelId());
                    modelPo.setIsValid(generalModelDTO.getIsValid());
                    modelPo.setCreatedBy("-1");
                    modelPo.setBrandId(Long.parseLong(seriesDictVO.getBrandId().toString()));
                    modelPo.setSeriesId(Long.parseLong(seriesDictVO.getSeriesId().toString()));
                    modelPo.setUpdatedAt(LocalDateTime.now());
                    modelPo.setRecordVersion(oldModelPo.getRecordVersion());
                    modelPo.setIsDeleted(generalModelDTO.getIsDelete() == null ? 0 : generalModelDTO.getIsDelete());
                    logger.debug("开始更新车型数据:{}", modelPo);
                    modelMapper.updateById(modelPo);
                }
            }
        } else {
            throw new ServiceBizException("厂端传来的车型数据的缺失！");
        }
    }

    @Override
    public List<ModelCacheVO> getAllModelByAppId(String appId) {
        LambdaQueryWrapper<ModelPO> query = new QueryWrapper<ModelPO>().lambda().eq(ModelPO::getAppId, appId);
        List<ModelPO> modelPos = this.modelMapper.selectList(query);
        return BeanMapperUtil.copyList(modelPos, ModelCacheVO.class);
    }

    /**
     * 品系型查询界面车型下拉框
     *
     * @param brandsId
     * @param seriesId
     * @author Tansj
     * @since 2019/11/18
     */
    @Override
    public List<ModelDictVO> queryModelDictAll(String brandsId, String seriesId) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map<String, Object> queryParam = new HashMap<>();
        queryParam = brandService.setLoginInfoParam(queryParam, loginInfoDto);
        queryParam.put("brandsId", brandsId);
        queryParam.put("seriesId", seriesId);
        return modelMapper.queryModelDictAll(queryParam);
    }

    /**
     * 新增编辑界面本店面车型下拉框
     *
     * @param brandsId
     * @param seriesId
     * @author Tansj
     * @since 2019/11/18
     */
    @Override
    public List<ModelDictVO> queryModelDictOwner(String brandsId, String seriesId) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("brandsId", brandsId);
        queryParam.put("seriesId", seriesId);
        queryParam = brandService.setLoginInfoParam(queryParam, loginInfoDto);
        // 在新增编辑界面，车系下拉框为本店面的所有有效车系（不包括无效）
        queryParam.put(BasedataCommonConstants.IS_VALID, BaseDataDictConstants.IS_VALID);
        return modelMapper.queryModelDictOwner(queryParam);
    }
    
    /**
     * 新增编辑界面本店面配置下拉框
     *
     * @param brandsId
     * @param seriesId
     * @param modelId
     * @author zhangys
     * @since 2020/2/25
     */
    @Override
    public List<PackageDictVO> queryPackageDictOwner(String brandsId, String seriesId,String modelId) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("brandsId", brandsId);
        queryParam.put("seriesId", seriesId);
        queryParam.put("modelId", modelId);
        queryParam = brandService.setLoginInfoParam(queryParam, loginInfoDto);
        // 在新增编辑界面，车系下拉框为本店面的所有有效车系（不包括无效）
        queryParam.put(BasedataCommonConstants.IS_VALID, BaseDataDictConstants.IS_VALID);
        return modelMapper.queryPackageDictOwner(queryParam);
    }

    /**
     * 新增编辑界面厂端车型下拉框
     *
     * @param brandsId
     * @param seriesId
     * @author Tansj
     * @since 2019/11/18
     */
    @Override
    public List<ModelDictVO> queryDcsModelDictOwner(String brandsId, String seriesId) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("brandsId", brandsId);
        queryParam.put("seriesId", seriesId);
        queryParam = brandService.setLoginInfoParam(queryParam, loginInfoDto);
        // 在新增编辑界面，车系下拉框为厂端的所有有效车系
        queryParam.put("isValid", BaseDataDictConstants.IS_VALID);
        return modelMapper.queryDcsModelDictOwner(queryParam);
    }

    /**
     * 新增编辑界面厂端车型下拉框
     *
     * @param brandsId
     * @param seriesId
     * @author Tansj
     * @since 2019/11/18
     */
    @Override
    public List<ModelDictVO> queryDcsModelDictAll(String brandsId, String seriesId) {
        Map<String, Object> queryParam = new HashMap<>();
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        queryParam.put("seriesId", seriesId);
        queryParam.put("brandsId", brandsId);
        //查询授权车型
//        List<Map<String, Object>> modelList = dealerAttachModelService.selectListBySql(queryCondition);

        queryParam = brandService.setLoginInfoParam(queryParam, loginInfoDto);
        return modelMapper.queryDcsModelDictOwner(queryParam);
    }

    /**
     * 根据经销商授权显示车型
     *
     * @param  queryParam 显示的车型对象map格式
     * @author wangsht
     * @since 2020-12-17
     */
    @Override
    public List<ModelDictVO> queryDcsModelDictAll(Map<String, Object> queryParam) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        queryParam = brandService.setLoginInfoParam(queryParam, loginInfoDto);
        return modelMapper.queryDcsModelDictOwner(queryParam);
    }
    
    /**
     * 根据查询条件返回对应的车型数据
     * 
     * @param modelQueryDTO
     * @return java.util.List<com.yonyou.cyxdms.basedata.service.vo.model.VehicleProductModelVO>
     * @author caozx
     * @since 2020/12/8
     */
    @Transactional(readOnly = true)
    @Override
    public List<VehicleProductModelVO> queryVehicleProductModel(ModelQueryDTO modelQueryDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map<String, Object> queryParam = modelQueryDTO.toMaps();
        queryParam = brandService.setLoginInfoParam(queryParam, loginInfoDto);
        logger.info("查询车系IPage的queryParam:---------{}", queryParam);
        return modelMapper.queryVehicleProductModel(queryParam);
    }

    @Override
    public VsProductDlrVO getModelNew(String modelCode,String appId) {
        return modelMapper.getModelNew(modelCode,appId);
    }

    @Override
    public ArrayList<ModelDictVO> queryModelDictAll() {
        return modelMapper.queryModelDictAllNoPar();
    }

    @Override
    public List<SeriesModelTreeDto> getSeriesModelTree(){
        List<SeriesModelTreeDto> list = new ArrayList<>();
        Map<String, Object> queryParam = new HashMap<>();
        List<BrandPO> brandPos = brandMapper.selectList(new LambdaQueryWrapper<BrandPO>().eq(BrandPO::getAppId, CommonConstant.APP_ID_RL));
        List<Long> brandIdList = brandPos.stream().map(t -> t.getBrandId()).collect(Collectors.toList());
        queryParam.put(BasedataCommonConstants.DEALER_BRNAND_LIST, brandIdList);
        queryParam.put("appId", CommonConstant.APP_ID_RL);
        List<SeriesCacheVO> seriesCaches = seriesMapper.querySeriesByCondition(queryParam);
        seriesCaches.forEach(t -> {
            SeriesModelTreeDto dto = new SeriesModelTreeDto();
            dto.setValue(t.getSeriesId());
            dto.setLabel(t.getSeriesCode() + "-" + t.getSeriesName());
            List<ModelPO> modelPos = modelMapper.selectList(new LambdaQueryWrapper<ModelPO>().eq(ModelPO::getAppId, CommonConstant.APP_ID_RL)
                    .eq(ModelPO::getSeriesId, t.getSeriesId()));
            List<SeriesModelTreeDto> children = new ArrayList<>();
            modelPos.forEach(m -> {
                SeriesModelTreeDto modelDto = new SeriesModelTreeDto();
                modelDto.setValue(m.getModelId());
                modelDto.setLabel(m.getModelCode() + "-" + m.getModelName());
                children.add(modelDto);
            });
            dto.setChildren(children);
            list.add(dto);
        });
        return list;
    }
}
